<template>
  <div>
    <el-upload
      class="avatar-uploader"
      :accept="accept"
      :action="uploadUrl"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :on-change="handleChange"
      :headers="header"
      :data="{
        isCompleteUrl: props.isCompleteUrl,
        isReserveName: props.isReserveName,
      }"
      auto-upload
      :multiple="limit == 1 ? false : true"
      :limit="props.limit"
    >
      <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
    <span class="c_999"
      >建议尺寸：（{{ props.width }}x{{ props.height }}）*n</span
    >
    <div class="flex_wp m_top10">
      <div
        v-for="(item, index) in props.imageUrl"
        class="p_rel flex_cc m_bottom10 m_right10"
      >
        <!-- {{ props.uploadUrl }} -->
        <!-- 非常规文件 需权限 + 接口调用-->
        <el-tooltip
          v-if="props.uploadUrl != ''"
          :content="fileNames[index]"
          placement="bottom"
        >
          <div
            @click="download(item)"
            @mouseenter="down_index = index"
            @mouseleave="down_index = Number"
            :style="{ width: props.width + 'px', height: props.height + 'px' }"
          >
            <div v-show="down_index == index" class="down_icon flex_cc">
              <el-icon :size="30" color="#777"><Download /></el-icon>
            </div>
            <img
              src="@/assets/img/file_default.png"
              :style="{
                width: props.width + 'px',
                height: props.height + 'px',
              }"
            />
          </div>
        </el-tooltip>

        <!-- 普通文件 -->
        <div v-else>
          <a
            v-if="!img_list.includes((item as any).split('.').at(-1))"
            :href="(item as any)"
            @mouseenter="down_index = index"
            @mouseleave="down_index = Number"
            :style="{ width: props.width + 'px', height: props.height + 'px' }"
          >
            <div v-show="down_index == index" class="down_icon flex_cc">
              <el-icon :size="30" color="#777"><Download /></el-icon>
            </div>
            <img
              src="@/assets/img/file_default.png"
              :style="{
                width: props.width + 'px',
                height: props.height + 'px',
              }"
            />
          </a>
          <el-image
            v-else
            :style="{ width: props.width + 'px', height: props.height + 'px' }"
            :src="item"
            :preview-src-list="[item]"
            fit="scale-down"
            class="border"
            append-to-body
          ></el-image>
        </div>

        <!-- <el-icon :size="20" class="delete_icon" @click="delete_item(index)"
          ><delete-filled
        /></el-icon> -->
        <div class="delete_icon">
          <img
            @mouseenter="delete_index = index"
            v-if="delete_index != index"
            src="@/assets/img/tabs_close_1.png"
            style="width: 16px; height: 16px; border-radius: 50%"
            alt=""
          />
          <img
            v-if="delete_index == index"
            @click="delete_item(index)"
            @mouseleave="delete_index = -1"
            src="@/assets/img/tabs_close_2.png"
            style="width: 16px; height: 16px; border-radius: 50%"
            alt=""
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { DeleteFilled, Download } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getBaseURL } from '@/service/BaseURL'
import serviceApi from '@/service/api'
import { ref, computed, toRefs } from 'vue'
import { getCookie } from '@/utils/cookie'
import EventBus from '@/utils/EventBus'
import axios from '@/service/HttpRequest'
const uploadUrl = computed(() => {
  // 上传 地址  判断是否有特殊地址
  return props.uploadUrl != ''
    ? getBaseURL() + props.uploadUrl
    : getBaseURL() + serviceApi.upload
})
const delete_index = ref(-1)
const header = { Authorization: getCookie('bimai_admin_token') }
const props = defineProps({
  limit: {
    type: Number,
  },
  imageUrl: {
    type: Array,
    default: [],
  },
  width: {
    type: Number,
    default: '48',
  },
  height: {
    type: Number,
    default: '48',
  },
  accept: {
    type: String,
    default: '',
  },
  uploadUrl: {
    // 特殊上传地址
    type: String,
    default: '',
  },
  downloadUrl: {
    // 特殊下载地址
    type: String,
    default: '',
  },
  fileNames: {
    type: Array,
    default: [],
  },
  isCompleteUrl: {
    type: Boolean,
    default: true,
  },
  isReserveName: {
    type: Boolean,
    default: true,
  },
})
const img_list = [
  'png',
  'jpg',
  'jpeg',
  'gif',
  'svg',
  'psd',
  'fpx',
  'ai',
  'apng',
]
const { accept, downloadUrl, fileNames } = toRefs(props)
const down_index = ref()
const handleChange = (file, fileLists) => {
  console.log(file, fileLists)
  if (file.status == 'success') {
    fileLists.forEach((item) => {
      !fileNames.value.includes(item.name)
        ? fileNames.value.push(item.name)
        : ''
    })
  }
}
const handleAvatarSuccess = (res) => {
  console.log(res)
  if (res.code == 200) {
    if (props.limit == 1) {
      props.imageUrl[0] = res.data.url
    } else {
      props.imageUrl.push(res.data.url)
    }
    EventBus.emit('uploadSucc')
    return
  } else {
    ElMessage.error(res.data.message)
  }
}
const download = (e) => {
  axios
    .request({
      url: downloadUrl.value + '/' + e,
      method: 'get',
      responseType: 'blob',
    })
    .then((res1) => {
      console.log(res1)
      const blob = new Blob([res1 as any]) // res.data 为接口返回的数据，依实例而行
      const URL = window.URL.createObjectURL(blob) // 生成一个 Blob URL
      const fileName = fileNames.value[down_index.value] // 文件名+后缀
      const listNode = document.createElement('a')
      listNode.download = fileName as any
      listNode.style.display = 'none'
      listNode.href = URL // 文件流生成的url
      document.body.appendChild(listNode)
      listNode.click() // 模拟在按钮上实现一次鼠标点击
      window.URL.revokeObjectURL(listNode.href) // 释放 URL 对象
      document.body.removeChild(listNode) // 移除 a 标签
    })
}
const delete_item = (e) => {
  props.imageUrl.splice(e, 1)
  fileNames.value.splice(e, 1)
}
const beforeAvatarUpload = (rawFile) => {
  console.log(rawFile, accept.value)
  //   if (fileNames.value.includes(rawFile.name)) {
  //     ElMessage.error('请勿重复上传！')
  //     return false
  //   }
  if (
    // 大样图 文件类型判断
    accept.value == 'dwg' &&
    rawFile.name.split('.')[rawFile.name.split('.').length - 1] != 'dwg'
  ) {
    ElMessage.error('请上传dwg格式文件')
    return false
  } else if (
    // 压缩包文件判断
    accept.value == 'rar,zip,7z' &&
    !accept.value
      .split(',')
      .includes(rawFile.name.split('.')[rawFile.name.split('.').length - 1])
  ) {
    ElMessage.error('请上传rar、zip、7z等格式文件')
    return false
  }
  return true
}
</script>

<style scoped>
.border {
  border: 1px solid #ccc;
}
.delete_icon {
  cursor: pointer;
  position: absolute;
  right: 4px;
  top: 4px;
  z-index: 101;
}
.avatar-uploader .avatar {
  width: 48px;
  height: 48px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 48px;
  height: 48px;
  text-align: center;
}
</style>
